题目描述

原题

Description:
Determine whether an integer is a palindrome. An integer is a palindrome when it reads the same backward as forward.

Example 1:

Input: 121
Output: true

Example 2:

Input: -121
Output: false
Explanation: From left to right, it reads -121. From right to left, it becomes 121-. Therefore it is not a palindrome.

Example 3:

Input: 10
Output: false
Explanation: Reads 01 from right to left. Therefore it is not a palindrome.

Follow up:
Could you solve it without converting the integer to a string?

原题翻译

原题

描述:
确定整数是否是回文。当它向前读取向后时,整数是回文。

例1:

输入: 121
输出: true

例2:

输入: -121
输出: false
解释: 从左到右读取它,为-121。从右到左读取它,为121-。因此它不是回文。

例3:

输入: 10
输出: false
解释: 从左到右读取它,为10。从右到左读取它,为01。因此它不是回文。

提升:
你可以不将整数转换为字符串解决它吗?

解法一

主要思想

把x倒置,再与x比较即可。

运行速度:超过了100%的解答。

内存使用:超过了5.02%的解答。

源码

1
2
3
4
5
6
7
8
9
10
11
12
public class Solution {
public boolean isPalindrome(int x) {
if(x < 0)
return false;
int a = 0, b = x;
while(b != 0) {
a = a * 10 + b % 10;
b /= 10;
}
return a == x;
}
}